<template>
    <div class="image-loader-container">
        <img class="placeholder" :src="placeholder" v-if="!is_transitionend" />
        <img
            :src="src"
            @load="loaded"
            :style="{
                opacity: is_loaded ? 1 : 0,
                transition: `opacity ${duration}ms`
            }"
        />
    </div>
</template>

<script>
export default {
    props: {
        src: {
            type: String,
            required: true
        },
        placeholder: {
            type: String,
            required: true
        },
        duration: {
            // 动画时长
            type: Number,
            default: 500
        }
    },
    data() {
        return {
            is_loaded: false, // 图片是否加载完成
            is_transitionend: false // 过渡动画是否完成
        }
    },
    methods: {
        loaded() {
            this.is_loaded = true
            setTimeout(() => {
                this.is_transitionend = true
                this.$emit("img_load")
            }, this.duration)
        }
    }
}
</script>

<style lang="less">
.image-loader-container {
    width: 100%;
    height: 100%;
    position: relative;
    img {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        &.placeholder {
            filter: blur(10px);
        }
    }
}
</style>
